package cn.com.infcn.httpclientTest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * Hello world!
 *
 */
public class App {

	/**
	 * 1.1. 请求执行
	 * 
	 * HttpClient最基本的功能就是执行Http方法。一个Http方法的执行涉及到一个或者多个Http请求/Http响应的交互，
	 * 通常这个过程都会自动被HttpClient处理
	 * ，对用户透明。用户只需要提供Http请求对象，HttpClient就会将http请求发送给目标服务器，
	 * 并且接收服务器的响应，如果http请求执行不成功，httpclient就会抛出异样。
	 * 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void test1() throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("http://www.cninfo.com.cn/cninfo-new/announcement/query?stock=&searchkey=&plate=&category=category_jy_szsh%3B&trade=&column=szse&columnTitle=%E5%8E%86%E5%8F%B2%E5%85%AC%E5%91%8A%E6%9F%A5%E8%AF%A2&pageNum=1&pageSize=30&tabName=fulltext&sortName=&sortType=&limit=&showTitle=category_jy_szsh%2Fcategory%2F%E4%BA%A4%E6%98%93&seDate=1990-01-01+~+2016-11-24");
		CloseableHttpResponse response = httpClient.execute(httpPost);

		try {
			Header[] headers = response.getAllHeaders();
			for (Header header : headers) {
				System.out.println(header.getName() + ":" + header.getValue());
			}

			System.out.println("=======================");
			//
			Locale locale = response.getLocale();
			System.out.println(locale.getDisplayName());
			System.out.println(locale.getCountry());
			System.out.println(locale.getDisplayLanguage());
			System.out.println(locale.getDisplayScript());
			System.out.println(locale.getDisplayVariant());
			System.out.println(locale.getLanguage());
			System.out.println(locale.getScript());

			// 状态行
			StatusLine sl = response.getStatusLine();
			System.out.println(sl.getStatusCode() + "==" + sl.getProtocolVersion());

			response.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("======================================");
		
		try {
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			try {
				byte[] b = new byte[1024];
				while (inputStream.read(b) != -1) {
					System.out.println(new String(b));
				}
			} catch (Exception e) {
			} finally {
				inputStream.close();
			}
		} catch (Exception e) {
		} finally {
			response.close();
			httpClient.close();
		}
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		test1();
	}
}
